using System;
using System.Windows.Forms;

namespace Pegasus.Windows.Forms.Explorer
{
	internal class FormsExplorerList : ListView, IExplorerList
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="FormsExplorerList"/> class.
		/// </summary>
		public FormsExplorerList()
		{
			// Add Single Column by default for names
			ColumnHeader column = new ColumnHeader();
			column.Text = "Name";
			column.Width = 250;
			
			Columns.Add( column );
		}

		/// <summary>
		/// Gets or sets the selected list node.
		/// </summary>
		/// <value>The selected list node.</value>
		public ExplorerNode[] SelectedListNodes
		{
			get
			{
				int x = 0;
				int count = SelectedItems.Count;
				ExplorerNode[] nodes = new ExplorerNode[ count ];

				foreach( ListViewItem item in SelectedItems )
				{
					nodes[ x++ ] = (ExplorerNode) item.Tag;
				}

				return nodes;
			}

			set
			{
				ClearSelection();
				if( value != null )
				{
					foreach( ExplorerNode node in value )
					{
						ListViewItem item = Items[ node.Text ];
						if( item != null )
						{
							item.Selected = true;
						}
					}
				}
			}
		}

		/// <summary>
		/// Sets the nodes to display in the list.
		/// </summary>
		/// <param name="nodes">The nodes collection.</param>
		public void SetNodes( ExplorerNodeCollection nodes )
		{
			Items.Clear();

			foreach( ExplorerNode node in nodes )
			{
				ListViewItem item = new ListViewItem();
				item.Tag = node;
				item.Text = node.Text;
				item.ImageIndex = node.ImageIndex;

				Items.Add( item );
			}
		}

		/// <summary>
		/// Sets the image list for the icons in the list.
		/// </summary>
		/// <param name="smallImageList">The small image list.</param>
		/// <param name="largeImageList">The large image list.</param>
		public void SetImageList( ImageList smallImageList, ImageList largeImageList )
		{
			SmallImageList = smallImageList;
			LargeImageList = largeImageList;
		}

		/// <summary>
		/// Clears the selection.
		/// </summary>
		protected void ClearSelection()
		{
			foreach( ListViewItem item in Items )
			{
				item.Selected = false;
			}
		}
	}
}
